<?php

namespace App\Http\Middleware;

use App\Exceptions\PowerException;
use App\Util\AuthSupport;
use App\Util\LoginUtil;
use Closure;

class Permission
{
    protected $except = [

        '/api/admin/index/index',
        '/api/admin/index/welcome',
        '/api/admin/index/showlog',
        '/api/admin/index/menu',
        '/api/admin/login/logout',
        '/api/admin/group/index',
        '/api/admin/role/index',
        '/api/admin/admin_users/information',
        '/api/admin/admin_users/showinfo',
        '/api/admin/admin_routes/user_routes',
        '/api/admin/dictionary_code/index',
        '/api/admin/admin_users/index',
        '/api/admin/project_company/project_companys/index',
        '/api/admin/projects/projects/index',

    ];

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //检查是否需要验证权限
        if (!$this->isLogin()) {
            throw  new PowerException('没有登录', [], '/api/admin/login');
        }

        // 如果请求的模块在权限之内 | 在排除权限的功能模块之内 | ACTION_NAME的值为select
        if (($this->isPermission()) || $this->inExceptArray($request) || ACTION_NAME == 'select' ) {
            return $next($request);
        }
        throw new PowerException('没有权限', []);
    }

    /**
     * Determine if the request has a URI that should pass through CSRF verification.
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function inExceptArray($request)
    {
        foreach ($this->except as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            if ($request->fullUrlIs($except) || $request->is($except)) {
                return true;
            }
        }

        //查询列外路由
        $AdminMenuExceptModel = new \App\Models\AdminMenuExceptModel();
        $menu_except = $AdminMenuExceptModel::get()->toArray();

        $str = DIRECTORY_SEPARATOR;
        foreach ($menu_except as $v) {
            if ($v['method'] == '*') {//如果方法是*，则判断除方法外是否相等
                $beg_path = $request->path();
                if ($v['module'] . $str . $v['controller'] == substr($beg_path, 0, strrpos($beg_path, $str))) {
                    return true;
                }
            }
            $m_except = $str . $v['module'] . $str . $v['controller'] . $str . $v['method'];
            if ($m_except !== '/') {
                $m_except = trim($m_except, '/');
            }

            if ($request->fullUrlIs($m_except) || $request->is($m_except)) {
                return true;
            }
        }
        return false;
    }

    protected function isLogin()
    {
        //检查是否登陆
        return LoginUtil::getUserId();
    }

    protected function isPermission()
    {
        //定义控制器模块

        return LoginUtil::checkPower();

    }
}
